package com.dzsw.md5;

import com.dzsw.utils.DateUtil;
import com.dzsw.utils.GsonUtils;
import com.dzsw.utils.StringUtils;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * @author sunz
 * @version 1.0
 * @CreateTime 2021-06-17-10:30
 */
public class MD5Utils {

  public static String md5(String str) {
    return DigestUtils.md5Hex(str);
  }

  public static int random6Num() {
    return (int) ((Math.random() * 9 + 1) * 100000);
  }

  public static void main(String[] args) throws Exception {
    String pattern = "yyyy-MM-dd HH:mm:ss SSS";
    String testJson = getJsonData();
    System.out.println(testJson);
    String strDateTime = "2021-06-17 15:20:09 252";
    LocalDateTime ldt = DateUtil.parseLdt(strDateTime, pattern);
    String timeStamp = DateUtil.format(ldt, pattern);
    String transId = String.valueOf(ldt.toInstant(ZoneOffset.of("+8")).getEpochSecond());
    String token = genToken(timeStamp, transId, testJson);
    System.out.println(token);
    AuthHeader header = AuthHeader.builder()
        .appId(APP_ID)
        .timeStamp(timeStamp)
        .transId(transId)
        .token(token)
        .build();
    String headerJson = GsonUtils.objectToJson(header);
    System.out.println(headerJson);
    String headerBase64 = encodeBase64Str(headerJson);
    System.out.println(headerBase64);
  }

  private static final String APP_ID = "0a4ed8f0e2de48df8ac56db1ad041847";
  private static final String APP_SECRET = "f9db104e508140aba44dd9d7b4aa1790";

  public static String genToken(String timeStamp, String transId, String contentJson) {
    String str = StringUtils.combineStr("APP_ID", APP_ID, "TIMESTAMP", timeStamp, "TRANS_ID", transId,
        String.valueOf(random6Num()), contentJson, APP_SECRET);
    System.out.println(str);
    String token = md5(str);
    return token;
  }

  public static String getJsonData() throws Exception {
    String filePath = "D:\\test_data.txt";
    String line = "";
    BufferedReader br = null;
    StringBuilder sb = new StringBuilder();
    try {
      br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
      // 循环处理每一行
      while ((line = br.readLine()) != null) {
        sb.append(line);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (br != null) {
        br.close();
      }
    }
    return sb.toString();
  }


  public static String encodeBase64Str(String str) {
    return Base64.encodeBase64String(str.getBytes(StandardCharsets.UTF_8));
  }

}
